{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Many to One RNN with Fixed Sequence Length:\n",
    "\n",
    "In this tutorial we implement \n",
    "\n",
    "<img src=\"files/files/06.png\">\n",
    "\n",
    "\n",
    "*Fig1. Unfolded representation of the implemented RNN structure*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Import the required libraries:\n",
    "We will start with importing the required libraries to our Python environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# imports\n",
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Generate some data\n",
    "\n",
    "For this tutorial ...\n",
    "\n",
    "### 1.1. Data dimension\n",
    "Here, we specify the dimensions of the data samples which will be used in the code. Defining these variables makes it easier (compared with using hard-coded number all throughout the code) to modify them later. Ideally these would be inferred from the data that has been read, but here we just write the numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Data Dimensions\n",
    "input_dim = 1           # input dimension\n",
    "seq_max_len = 4         # sequence maximum length\n",
    "out_dim = 1             # output dimension"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2. Generate data and display the sizes\n",
    "Now we can use the defined helper function in \"train\" mode which loads the train and validation images and their corresponding labels. We'll also display their sizes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# ==========\n",
    "#  TOY DATA\n",
    "# ==========\n",
    "x_train = np.random.randint(0, 10, size=(100, 4, 1))\n",
    "y_train = np.sum(x_train, axis=1)\n",
    "\n",
    "x_test = np.random.randint(0, 10, size=(5, 4, 1))\n",
    "y_test = np.sum(x_test, axis=1)\n",
    "\n",
    "\n",
    "print(\"Size of:\")\n",
    "print(\"- Training-set size:\\t\\t{}\".format(len(y_train)))\n",
    "print(\"- Test-set size:\\t{}\".format(len(y_test)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get batches of samples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def next_batch(x, y, batch_size):\n",
    "    N = x.shape[0]\n",
    "    batch_indices = np.random.permutation(N)[:batch_size]\n",
    "    x_batch = x[batch_indices]\n",
    "    y_batch = y[batch_indices]\n",
    "    return x_batch, y_batch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Hyperparameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Parameters\n",
    "learning_rate = 0.01    # The optimization initial learning rate\n",
    "training_steps = 10000  # Total number of training steps\n",
    "batch_size = 10         # batch size\n",
    "display_freq = 1000     # Frequency of displaying the training results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Network configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "num_hidden_units = 10   # number of hidden units"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Create network helper functions \n",
    "### 4.1. Helper functions for creating new variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# weight and bais wrappers\n",
    "def weight_variable(shape):\n",
    "    \"\"\"\n",
    "    Create a weight variable with appropriate initialization\n",
    "    :param name: weight name\n",
    "    :param shape: weight shape\n",
    "    :return: initialized weight variable\n",
    "    \"\"\"\n",
    "    initer = tf.truncated_normal_initializer(stddev=0.01)\n",
    "    return tf.get_variable('W',\n",
    "                           dtype=tf.float32,\n",
    "                           shape=shape,\n",
    "                           initializer=initer)\n",
    "\n",
    "\n",
    "def bias_variable(shape):\n",
    "    \"\"\"\n",
    "    Create a bias variable with appropriate initialization\n",
    "    :param name: bias variable name\n",
    "    :param shape: bias variable shape\n",
    "    :return: initialized bias variable\n",
    "    \"\"\"\n",
    "    initial = tf.constant(0., shape=shape, dtype=tf.float32)\n",
    "    return tf.get_variable('b',\n",
    "                           dtype=tf.float32,\n",
    "                           initializer=initial)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2. Helper-function for creating a RNN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def RNN(x, weights, biases, num_hidden):\n",
    "    \"\"\"\n",
    "    :param x: inputs of size [batch_size, max_time, input_dim]\n",
    "    :param weights: matrix of fully-connected output layer weights\n",
    "    :param biases: vector of fully-connected output layer biases\n",
    "    :param num_hidden: number of hidden units\n",
    "    \"\"\"\n",
    "    cell = tf.nn.rnn_cell.BasicRNNCell(num_hidden)\n",
    "    outputs, states = tf.nn.dynamic_rnn(cell, x, dtype=tf.float32)\n",
    "    out = tf.matmul(outputs[:, -1, :], weights) + biases\n",
    "    return out"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Create the network graph\n",
    "### 5.1. Placeholders for the inputs (x) and corresponding labels (y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Placeholders for inputs(x), input sequence lengths (seqLen) and outputs(y)\n",
    "x = tf.placeholder(tf.float32, [None, seq_max_len, input_dim])\n",
    "y = tf.placeholder(tf.float32, [None, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2. Define the network"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# create weight matrix initialized randomely from N~(0, 0.01)\n",
    "W = weight_variable(shape=[num_hidden_units, out_dim])\n",
    "\n",
    "# create bias vector initialized as zero\n",
    "b = bias_variable(shape=[out_dim])\n",
    "\n",
    "# Network predictions\n",
    "pred_out = RNN(x, W, b, num_hidden_units)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3. Define the loss function and optimizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Define the loss function (i.e. mean-squared error loss) and optimizer\n",
    "cost = tf.reduce_mean(tf.square(pred_out - y))\n",
    "train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4. Initialize all variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Creating the op for initializing all variables\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = tf.InteractiveSession()\n",
    "sess.run(init)\n",
    "for i in range(training_steps):\n",
    "    x_batch, y_batch = next_batch(x_train, y_train, batch_size)\n",
    "    _, mse = sess.run([train_op, cost], feed_dict={x: x_batch, y: y_batch})\n",
    "    if i % display_freq == 0:\n",
    "        print('Step {}, MSE={}'.format(i, mse))\n",
    "# Test\n",
    "y_pred = sess.run(pred_out, feed_dict={x: x_test})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test\n",
    "y_pred = sess.run(pred_out, feed_dict={x: x_test})\n",
    "\n",
    "for i, x in enumerate(y_test):\n",
    "    print(\"When the ground truth output is {}, the model thinks it is {}\"\n",
    "          .format(y_test[i], y_pred[i]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After we are finished the testing, we will close the session to free the memory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thanks for reading! If you have any question or doubt, feel free to leave a comment in our [website](http://easy-tensorflow.com/)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
